package com.cyp.livelog.web;

import com.cyp.livelog.utils.DbUtils;
import com.cyp.livelog.vo.ArticleVo;
import com.mysql.jdbc.StringUtils;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 日月星辰
 * @date 2020/12/15 20:34
 * @description
 */
@WebServlet("/article")
public class ArticleAction extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action = req.getParameter("a");
    if (StringUtils.isNullOrEmpty(action)) {

    } else if (action.equals("details")) {
    }
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action = req.getParameter("a");
    if (StringUtils.isNullOrEmpty(action)) {
      details(req, resp);
    } else if (action.equals("details")) {
      details(req, resp);
    }
  }

  private void details(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //详情
    String id = req.getParameter("id");
    if (StringUtils.isNullOrEmpty(id)) {
      req.setAttribute("message", "不存在的文章！");
      req.getRequestDispatcher("/fail.jsp").forward(req, resp);
      return;
    }
    ResultSet res = DbUtils.query("select a.id,u.nickname,c.name,a.title,a.content,a.create_time,a.update_time "
        + " from article a left join article_class c on a.class_id=c.id"
        + " left join user u on a.username=u.username where a.id=?", Integer.valueOf(id));
    try {
      res.next();
      if (res.getString(4) == null) {
        req.setAttribute("message", "不存在的文章！");
        req.getRequestDispatcher("/fail.jsp").forward(req, resp);
        return;
      }
      ArticleVo vo = new ArticleVo();
      vo.setId(res.getInt(1));
      vo.setNickname(res.getString(2));
      vo.setClassName(res.getString(3));
      vo.setTitle(res.getString(4));
      vo.setContent(res.getString(5).replaceAll("\n", "<br>")
          .replaceAll("\t","&nbsp;&nbsp;"));
      vo.setCreateTime(res.getDate(7) != null ? res.getDate(7) : res.getDate(6));
      req.setAttribute("vo", vo);
      req.getRequestDispatcher("/WEB-INF/article/details.jsp").forward(req, resp);
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

}
